package com.exam.demo.utils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Base64;

public class TokenUtils {

    private static final String TOKEN_KEY = "myToken";

    private static final String SECRET_KEY = "9527";


    // 生成Token
    public static String generateToken(String userId) {
        String tokenData = userId + "_";

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest((tokenData + SECRET_KEY).getBytes(StandardCharsets.UTF_8));
            String token = Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
            return token + "#" + userId;
        } catch (NoSuchAlgorithmException e) {
            // 处理加密算法不支持的异常
            e.printStackTrace();
        }

        return null;
    }

    // 校验Token
    public static boolean validateToken(String userId,String token) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            byte[] hash = md.digest((userId + "_" + SECRET_KEY).getBytes(StandardCharsets.UTF_8));
            String calculatedToken = Base64.getUrlEncoder().withoutPadding().encodeToString(hash);

            return token.equals(calculatedToken);
        } catch (NoSuchAlgorithmException e) {
            // 处理加密算法不支持的异常
            e.printStackTrace();
        }

        return false;
    }

    //判断Token是否过期
    public static boolean validateExpire(long timestamp) {


        return  true;

    }



    // 从请求头中获取 Token
    public static String getTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_KEY);
        return token;
    }

    // 将 Token 存储到请求头
    public static void setTokenToRequest(HttpServletRequest request, String token) {
        request.setAttribute(TOKEN_KEY, token);
    }
}

